package 多线程初阶.示例测试;

/**
 * notifyAll的使用示例
 */
public class TestDemo18 {
    static class WaitTask implements Runnable{
        Object locker=new Object();
        public WaitTask(Object locker){
            this.locker=locker;
        }
        @Override
        public void run() {
            synchronized (this.locker){
                while (true){
                    System.out.println(Thread.currentThread().getName()+"正在等待");
                    try {
                        locker.wait();//释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"结束等待");
                }
            }
        }
    }
    static class NotifyTask implements Runnable{
        Object locker=new Object();
        public NotifyTask(Object locker){
            this.locker=locker;
        }
        @Override
        public void run() {
            synchronized (this.locker){
                System.out.println(Thread.currentThread().getName()+"开始notify");
                //locker.notify();//只能唤醒一个
                locker.notifyAll();
                System.out.println(Thread.currentThread().getName()+"结束notify");
            }
        }
    }

    /**
     * 疑惑:虽然notifyAll唤醒了所有线程,但这三个线程竞争的是同一个锁,而且while循环是没有结束的
     * 显然是没有释放锁的,那么其余两个线程是如何拿到锁的呢
     */
    public static void main(String[] args) throws InterruptedException {
        Object locker=new Object();
        Thread waitThreadA=new Thread(new WaitTask(locker),"waitThreadA");
        Thread waitThreadB=new Thread(new WaitTask(locker),"waitThreadB");
        Thread waitThreadC=new Thread(new WaitTask(locker),"waitThreadC");
        Thread notifyThread=new Thread(new NotifyTask(locker),"notifyThread");
        waitThreadA.start();
        waitThreadB.start();
        waitThreadC.start();
        Thread.sleep(1000);
        notifyThread.start();;
    }
}
